import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:time/common/NotificationUtils.dart';
import 'package:time/routes/FinishedList/FinishedList.dart';
import 'package:time/routes/NotificationSeting/NotiSet.dart';

main() async {
  // 用于确保Flutter的widget绑定已经初始化
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化通知类
  NotificationUtils notificationUtils = NotificationUtils();
  await notificationUtils.initialize();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Time',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.amber),
        useMaterial3: true,
      ),
      debugShowCheckedModeBanner: false,
      home: const MyHomePage(title: 'Time'),
      navigatorKey: GlobalKey<NavigatorState>(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late FlutterLocalNotificationsPlugin ff;

  final NotificationUtils _notificationUtils = NotificationUtils();

  int timeSecond = 10 * 60; // 默认10分钟
  String second = "00";
  Timer time = Timer.periodic(const Duration(seconds: 1), (timer) {
    timer.cancel();
  });
  int lastTime = 10; // 默认10分钟
  bool initHidden = true;
  var timeSources = ["30", "20", "10"];

  // 开启倒计时 -- 按钮点击事件
  void timeBegin() {
    // 发送通知
    initHidden = false;
    timeCancel();
    time = Timer.periodic(const Duration(seconds: 1), (timer) {
      timeless();
    });
  }

  // 取消倒计时
  void timeCancel() {
    time.cancel();
  }

  // 停止倒计时 -- 按钮点击事件
  void timeStop() {
    timeCancel();
    resetTime(lastTime);
  }

  // 时间流逝
  void timeless() {
    setState(() {
      timeSecond--;
      second = (timeSecond % 60) <= 9
          ? "0${(timeSecond % 60)}"
          : "${(timeSecond % 60)}";
      if (timeSecond < 0) {
        // 时间结束
        timeStop();
        // 发送通知
        _notificationUtils.showNotification(
            title: "恭喜你完成了一个倒计时", body: "好的习惯从每一个专注的倒计时开始");
      }
    });
  }

  // 重置时间
  void resetTime(int minute) {
    setState(() {
      lastTime = minute;
      timeSecond = minute * 60;
      second = "00";
    });
  }

  bool showWidget() {
    if (initHidden) {
      return false;
    } else {
      return time.isActive;
    }
  }

  //可以操作的时间
  List<Widget> timeActions() {
    List<Widget> widgets = [];
    for (int i = 0; i < timeSources.length; i++) {
      String time = timeSources[i];
      widgets.insert(
          0,
          CupertinoButton(
            onPressed: () {
              resetTime(int.parse(time));
            },
            child: Text(
              time,
              style: TextStyle(
                  color: Colors.yellow[800],
                  fontSize: 50,
                  fontWeight: FontWeight.w300),
            ),
          ));
    }
    return widgets;
  }

  // 圆环进度条颜色
  Color? showColor() {
    var p = timeSecond / (lastTime * 60);
    if (p <= 0.15) {
      return Colors.red[900];
    } else if (p <= 0.35) {
      return Colors.red[800];
    } else if (p <= 0.4) {
      return Colors.red[700];
    } else if (p <= 0.45) {
      return Colors.red[600];
    } else if (p <= 0.5) {
      return Colors.red[500];
    } else if (p <= 0.65) {
      return Colors.red[400];
    } else if (p <= 0.75) {
      return Colors.red[300];
    } else if (p <= 0.85) {
      return Colors.red[200];
    }
    return Colors.red[100];
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ff = FlutterLocalNotificationsPlugin();
    AndroidInitializationSettings androidInitializationSettings =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    DarwinInitializationSettings darwinInitializationSettings =
        DarwinInitializationSettings();
    InitializationSettings initializationSettings = InitializationSettings(
        android: androidInitializationSettings,
        iOS: darwinInitializationSettings);
    ff.initialize(initializationSettings);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        actions: [
          Visibility(
              visible: false,
              child: PopupMenuButton<String>(
                itemBuilder: (context) {
                  return <PopupMenuEntry<String>>[
                    const PopupMenuItem(
                      value: "set",
                      child: Text("设置"),
                    ),
                    const PopupMenuItem(
                      value: "flist",
                      child: Text("已完成列表"),
                    )
                  ];
                },
                onSelected: (value){
                  if(value == 'set') {
                    // 定义新页面的Route对象
                    MaterialPageRoute newPageRoute =
                    MaterialPageRoute(builder: (context) => NotiSet(notificationUtils: _notificationUtils,));
                    // 使用Navigator.push方法跳转到新页面
                    Navigator.of(context).push(newPageRoute);
                  }else if (value == 'flist') {
                    // 定义新页面的Route对象
                    MaterialPageRoute newPageRoute =
                    MaterialPageRoute(builder: (context) => const FinishedList());
                    // 使用Navigator.push方法跳转到新页面
                    Navigator.of(context).push(newPageRoute);
                  }
                },
              ))
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      Container(
                        width: 320,
                        height: 320,
                        color: Colors.white10,
                        child: CircularProgressIndicator(
                          backgroundColor: Colors.black12,
                          strokeWidth: 7,
                          color: Colors.blue[400],
                          value: (1 - (timeSecond / (lastTime * 60))),
                          valueColor: AlwaysStoppedAnimation(showColor()),
                        ),
                      ),
                      Container(
                        width: MediaQuery.of(context).size.width,
                        height: 200,
                        child: Center(
                          child: Text(
                            "${timeSecond ~/ 60}" + ":" + second,
                            style: const TextStyle(
                                color: Colors.black,
                                fontSize: 100,
                                fontWeight: FontWeight.w300),
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 50,
                  ),
                  Visibility(
                    visible: !showWidget(),
                    child: Center(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: timeActions(),
                      ),
                    ),
                  ),
                  Visibility(
                    visible: !showWidget(),
                    child: CupertinoButton(
                      onPressed: timeBegin,
                      color: Colors.amber[700],
                      child: const Text(
                        '开 始',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 30,
                            fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),
                  Visibility(
                    visible: showWidget(),
                    child: const SizedBox(
                      height: 90,
                    ),
                  ),
                  Visibility(
                    visible: showWidget(),
                    child: CupertinoButton(
                      onPressed: timeStop,
                      color: Colors.red,
                      child: const Text(
                        '结 束',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 30,
                            fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
